﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities.Presentation.Model;
using System.Windows.Data;
using System.Activities;
using Microsoft.VisualBasic.Activities;
using System.Activities.Expressions;
using System.Windows.Controls;

namespace TransactionServer.ActivityDesign.Helpers
{
    class ComboBoxItemMultipleStringConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            foreach (var value in values)
            {
                if (value is ModelItem && ((ModelItem)value).GetCurrentValue() is InArgument<string>)
                {
                    ModelItem modelItem = value as ModelItem;
                    if (value != null)
                    {
                        InArgument<string> inArgument = modelItem.GetCurrentValue() as InArgument<string>;

                        if (inArgument != null)
                        {
                            Activity<string> expression = inArgument.Expression;
                            VisualBasicValue<string> vbexpression = expression as VisualBasicValue<string>;
                            Literal<string> literal = expression as Literal<string>;

                            if (literal != null)
                            {
                                return literal.Value.Replace("\"", "");
                            }
                            else if (vbexpression != null)
                            {
                                return vbexpression.ExpressionText.Replace("\"", "");
                            }
                        }
                    }
                    return null;
                }
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            var result = new List<object>();
            for (int i = 0; i < targetTypes.Length; i++)
            {
                if (targetTypes[i] == typeof(InArgument<string>))
                {
                    string itemContent = "\"" + (string)value + "\"";
                    VisualBasicValue<string> vbArgument = new VisualBasicValue<string>(itemContent);
                    InArgument<string> inArgument = new InArgument<string>(vbArgument);
                    result.Add(inArgument);
                }
                else
                {
                    result.Add(value);
                }
            }
            return result.ToArray();
        }
    }
}
